package com.ghosthigh.simpleaccount.servlet;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.ghosthigh.simpleaccount.server.annotations.Annotations;
import com.google.common.io.CharStreams;
import com.google.inject.Inject;
import com.google.inject.Provider;
import com.google.inject.Singleton;

@Singleton
@SuppressWarnings("serial")
public class HtmlServlet extends HttpServlet {

  private final Provider<String> htmlPathProvider;

  @Inject
  public HtmlServlet(@Annotations.StaticHtml Provider<String> htmlPathProvider) {
    this.htmlPathProvider = htmlPathProvider;
  }

  @Override
  protected void doGet(HttpServletRequest req, HttpServletResponse resp)
      throws ServletException, IOException {
    resp.setHeader("XGhost-internal", htmlPathProvider.get());
    ServletContext context = getServletContext();

    InputStream is = context.getResourceAsStream(htmlPathProvider.get());
    if (is == null) {
      doPageNotFound(resp);
    }

    resp.getWriter().write(CharStreams.toString(new InputStreamReader(is)));
  }

  private void doPageNotFound(HttpServletResponse resp) throws IOException {
    resp.sendError(HttpServletResponse.SC_NOT_FOUND);
  }
}
